package com.example.administrator.myapplication;

import android.content.ContentResolver;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

import com.theartofdev.edmodo.cropper.CropImage;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.net.URISyntaxException;

import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class MainActivity extends AppCompatActivity {
    private static final String TAG = "MainActivity";
    private Uri imageUri;
    private Uri resultUri;
    private EditText etFooodNAME;
    private String realFileName;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    public void takePhoto(View view) throws IOException {
        //1.准备uri  保存拍照之后的结果文件 ，必须是一个新文件
        File file = new File(getExternalCacheDir(), "image.jpg");
        if (file.exists()) {
            file.delete();
        }
        file.createNewFile();
        //将file转换为Uri

        imageUri = Uri.fromFile(file);

        //启动拍照程序
        Intent intent = new Intent();
        intent.setAction(MediaStore.ACTION_IMAGE_CAPTURE);
        //指定拍照程序照片存放的文件Uri
        intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
        //是有那个请求码101，启动拍照程序
        startActivityForResult(intent, 101);
    }

    public void cropPhoto(View view) {
        CropImage.activity(imageUri).start(this);
    }

    public void uploadPhoto(View view){
        //创建线程
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    //准备上传的文件对象
                String s=resultUri.toString();

                Log.e(TAG,"run:"+s);
                URI uri= null;

                    uri = new URI(s);
                    File file=new File(uri);

                    //构建一个MultipartBody
                    //(1)构建RequestBody
                    RequestBody body=RequestBody.create(MediaType.parse("image/png"),file);

                    //（2）构建
                    MultipartBody multipartBody=new MultipartBody.Builder()
                            .setType(MultipartBody.FORM)
                            .addFormDataPart("file","image.jpg",body)
                            .build();
                    //构建请求Request对象
                    Request request=new Request.Builder()
                            .url("http://10.1.63.232:8080/RestaurantServer/File/doUpload")
                            .post(multipartBody)
                            .build();
                    //执行请求，处理结果
                    OkHttpClient client=new OkHttpClient();
                    Response response=client.newCall(request).execute();

                    String data=response.body().string();
                    //将data转换为jsonobject
                    JSONObject jsonObject=new JSONObject(data);
                    realFileName = jsonObject.getString("realFileName");

                    Log.e(TAG,"run:"+data);
                } catch (URISyntaxException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }
        }).start();

    }
    public  void addPhoto(View view) throws JSONException {
        //获取用户输入的数据，构建上传的数据json字符串，完成上传，并处理结果
        EditText etFooodNAME=(EditText) findViewById(R.id.id_et_food_name);
        EditText etFooodPrice=(EditText) findViewById(R.id.id_et_food_price);
        EditText etFooodDesc=(EditText) findViewById(R.id.id_et_food_desc);

        String foodName=etFooodNAME.getText().toString();
        String sfoodPrice=etFooodPrice.getText().toString();
        int foodPrice=Integer.parseInt(sfoodPrice);
        String foodDesc=etFooodDesc.getText().toString();
        String foodPic=realFileName;//图片文件名字   利用字段变量共享数据

        //准备json
        JSONObject object=new JSONObject();
        object.put("foodName",foodName);
        object.put("foodPrice",foodPrice);
        object.put("foodDesc",foodDesc);
        object.put("foodPic",foodPic);
      final String jsons=object.toString();//将json对象转换为json字符串

        //完成上传
        new Thread(new Runnable() {
            @Override
            public void run() {
                OkHttpClient client=new OkHttpClient();

                RequestBody body= RequestBody.create(MediaType.parse("application/json"),jsons);
                String url="http://10.1.63.232:8080/RestaurantServer/Food/addFood";

                Request request=new Request.Builder()
                        .url(url)  //网址
                        .post(body)  //提交数据
                        .build();
                try {
                    Response response= client.newCall(request).execute();
                    String data = response.body().string();
                    Log.e(TAG,"run:"+data);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == RESULT_OK) {
            InputStream inputStream = null;
            try {
                //通过contentResolver,获取Uri对象的字节流
                inputStream = getContentResolver().openInputStream(imageUri);
                //从输入流，构造bitmap
                Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
                //从布局文件中，获取显示图片的ImageView
                ImageView photoImage = (ImageView) findViewById(R.id.id_iv_photo);
                //将bitmap显示到phototImage
                photoImage.setImageBitmap(bitmap);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }

        } else if (resultCode == RESULT_CANCELED) {
            Toast.makeText(this, "取消了", Toast.LENGTH_SHORT).show();
        }

        if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE) {
            CropImage.ActivityResult result = CropImage.getActivityResult(data);
            resultUri = result.getUri();
            //通过contentResolver,获取Uri对象的字节流
            InputStream inputStream = null;

            try {
              inputStream= getContentResolver().openInputStream(resultUri);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
            //从输入流，构造bitmap
            Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
            //从布局文件中，获取显示图片中的ImageView
            ImageView photoImage = (ImageView) findViewById(R.id.id_iv_photo);
            //将bitmap显示到photoImage中
            photoImage.setImageBitmap(bitmap);
        }
    }
}













